package com.wfk.plat.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.wfk.jwt.JWT;
import com.wfk.plat.mapping.MappingUtils;
import com.wfk.utils.Login;
import com.wfk.utils.ResponseData;
import com.wfk.utils.TokenUtils;

/**
 * JWT拦截器 
 * @author TianPeng
 *
 */
public class TokenInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setCharacterEncoding("utf-8");
		String token = TokenUtils.getToken(request) ;
		//token不存在
		if(null != token) {
			Login login = JWT.unsign(token, Login.class);
			String loginId = request.getParameter("loginId");
			//解密token后的loginId与用户传来的loginId不一致，一般都是token过期
			if(null != loginId && null != login) {
				if(Integer.parseInt(loginId) == login.getId()) {
					return true;
				}
				else{
					String accept = request.getHeader("Accept");
					if(accept.indexOf("application/json") != -1) {
						//是json请求
						response.setContentType("application/json");
						response.getWriter().print(JSON.toJSONString(ResponseData.forbidden()));
						response.getWriter().close(); 
						return false ;
					}
					response.sendRedirect(MappingUtils.login);
					return false;
				}
			}
			else{
				String accept = request.getHeader("Accept");
				if(accept.indexOf("application/json") != -1) {
					//是json请求
					response.setContentType("application/json");
					response.getWriter().print(JSON.toJSONString(ResponseData.forbidden()));
					response.getWriter().close(); 
					return false ;
				}
				
				response.sendRedirect(MappingUtils.login);
				return false;
			}
		}else{
			String accept = request.getHeader("Accept");
			if(accept.indexOf("application/json") != -1) {
				//是json请求
				response.setContentType("application/json");
				response.getWriter().print(JSON.toJSONString(ResponseData.forbidden()));
				response.getWriter().close(); 
				return false ;
			}
			response.sendRedirect(MappingUtils.login);
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}


}
